package com.guodi.model.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.AjaxResult;
import com.guodi.common.utils.PageData;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.tool.utils.Func;
import com.guodi.model.entity.*;
import com.guodi.model.service.*;
import com.guodi.model.utils.ExcelUtil;
import com.guodi.model.utils.JudgeWarnRuleUtil;
import com.guodi.model.utils.RegularUtils;
import com.guodi.model.utils.TimeUtils;
import com.guodi.system.feign.IUserClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @描述：指标填报表控制类
 * @作者: 代鹏刚
 * @日期: 2020-10-20
 */
@RestController
@RequestMapping("/IdtMonitorFill")
@Api(value = "API - IdtMonitorFillController", description = "指标填报表")
public class IdtMonitorFillController extends BaseController {

    @Resource
    public IIdtMonitorFillService idtMonitorFillService;
    @Resource
    private IIdtMonitorValueService iIdtMonitorValueService;
    @Resource
    private IIdtIndicatorsService iIdtIndicatorsService;
    @Resource
    private IIdtReportValueService iIdtReportValueService;
    @Resource
    private IIdtValueUpdateService iIdtValueUpdateService;

    @Resource
    private IIdtWarnRuleService iIdtWarnRuleService;
    @Resource
    public IIdtTargetValueService idtTargetValueService;
    @Resource
    public IIdtYearRelevanceService iIdtYearRelevanceService;

    @Resource
    private IIdtReportFileService iIdtReportFileService;

    @Resource
    private IIdtReportFileService idtReportFileService;

    @Resource
    IUserClient iUserClient;

    @Resource
    public IIdtIndicatorsTypeService iIdtIndicatorsTypeService;

    /**
    * @描述: 根据实体属性查询
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020-10-20
    **/
    @PostMapping("/listByEntity")
    @ApiOperation(value = " 根据实体属性查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "indicatorsId", value = "指标ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userDivision", value = "行政区划代码(多个使用逗号隔开)", required = true, dataType = "string", paramType = "query")
    })
    public AjaxResult listByEntity(String indicatorsId, String userDivision){
        //存储指标集合
        List<String> ids = new ArrayList<>();
        IdtIndicators idtIndicators = iIdtIndicatorsService.getById(indicatorsId);
        if(StringUtils.isNotBlank(idtIndicators.getDatasource()) && idtIndicators.getDatasource().equals("formula")){
            if(StringUtils.isNotBlank(idtIndicators.getCalculateResult())){
                List<String> codes = RegularUtils.extractString(idtIndicators.getCalculateResult());
                ids = iIdtIndicatorsService.listEntityByCode(codes);
                ids.add(indicatorsId);
            }else {
                return new AjaxResult(StatusCode.ERROR_CODE_40005,"该复合指标请先配置计算公式");
            }
        }else {
            ids.add(indicatorsId);
        }
        List<IdtMonitorFill> idtMonitorFills = idtMonitorFillService.listByData(ids, userDivision.split(","));
        //获取行政区划
        PageData pageData = new PageData();
        List<PageData> divisionList = iIdtIndicatorsService.listDivisionByEntity(pageData);
        Map<String, String> dictMap = new HashMap<>();
        for (PageData data : divisionList) {
            dictMap.put(data.get("code").toString(), data.get("name").toString());
        }
        idtMonitorFills = idtMonitorFills.stream().map(fill -> {
            if (indicatorsId.equals(fill.getIndicatorsId())) {
                fill.setDatasource("formula");
                fill.setSort(9999);
            } else {
                fill.setSort(0);
            }
            fill.setDivisionName(dictMap.get(fill.getDivisionCode()));
            return fill;
        }).collect(Collectors.toList());
        //按指标体系配置顺序排序
        idtMonitorFills = idtMonitorFills.stream().sorted(Comparator.comparing(IdtMonitorFill::getSort)).collect(Collectors.toList());
        Map<Integer, List<IdtMonitorFill>> resultMap = idtMonitorFills.stream().collect(Collectors.groupingBy(IdtMonitorFill::getIdIndex));
        Map<String, List<IdtMonitorFill>> result = new HashMap<>();
        for (Integer key : resultMap.keySet()) {
            List<IdtMonitorFill> idtMonitorFillList = resultMap.get(key);
            // 获取当前分类中value的ID集合
            List<String> allIds = idtMonitorFillList.stream().map(x->x.getIndicatorsId()).collect(Collectors.toList());
            // 获取分类中不存在的指标ID数据集
            List<String> resultIds = ids.stream().filter(x->!allIds.contains(x)).collect(Collectors.toList());
            if(resultIds.size() > 0){
                for (String id:resultIds) {
                    // 缺失指标上报值，则补充
                    IdtMonitorFill idtMonitorFill = new IdtMonitorFill();
                    idtMonitorFill.setId(UuidUtil.get32UUID());
                    idtMonitorFill.setYear(idtMonitorFillList.get(0).getYear());
                    idtMonitorFill.setMonitorTime(idtMonitorFillList.get(0).getMonitorTime());
                    idtMonitorFill.setDivisionCode(idtMonitorFillList.get(0).getDivisionCode());
                    idtMonitorFill.setIndicatorsId(id);
                    idtMonitorFill.setOrgId(idtMonitorFillList.get(0).getOrgId());
                    idtMonitorFillList.add(idtMonitorFill);
                }
            }
            // 按照当前的指标返回监测时间格式
            IdtMonitorFill monitorTime = idtMonitorFillList.stream().filter(x -> x.getIndicatorsId().equals(indicatorsId)).collect(Collectors.toList()).get(0);
            result.put(key+"-"+monitorTime.getMonitorTime(),idtMonitorFillList);
        }
        return new AjaxResult(result);
    }

    /**
     * @描述: 新增
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020-10-20
     **/
    @PostMapping("/save")
    @ApiOperation(value = "新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "formJson", value = "存放指标对象的json字符串", required = true, dataType = "string", paramType = "query")
    })
    public AjaxResult save(String formJson){
        List<IdtMonitorFill> idtMonitorFills = JSONObject.parseArray(formJson, IdtMonitorFill.class);
        if(null == idtMonitorFills || idtMonitorFills.size() == 0){
            return new AjaxResult(StatusCode.ERROR_CODE_40005,"参数格式错误，请检查");
        }
        // 数据检查
        AjaxResult checkDataLegitimate = this.checkDataLegitimate(idtMonitorFills);
        if (checkDataLegitimate != null){
            return checkDataLegitimate;
        }
        for (IdtMonitorFill idtMonitorFill : idtMonitorFills) {
            if (idtMonitorFill.getYear() == null && StringUtils.isNotBlank(idtMonitorFill.getMonitorTime().split("-")[0])) {
                idtMonitorFill.setYear(Integer.valueOf(idtMonitorFill.getMonitorTime().split("-")[0]));
            }
            if(idtMonitorFill.getCreateTime() == null){
                prepareData(idtMonitorFill, true);
            }else {
                prepareData(idtMonitorFill, false);
            }
            if(idtMonitorFill.getOrgId() == null){
                idtMonitorFill.setOrgId(this.getUser().getDeptId());
            }
        }
        // 基础指标需要更新至对应更新频率下的周期
        iIdtValueUpdateService.getNewestData(idtMonitorFills);
        // 分组过滤列表中重复的记录
        Map<String, List<IdtMonitorFill>> map = idtMonitorFills.stream().collect(Collectors.groupingBy(mf -> {
            return mf.getIndicatorsId() + mf.getDivisionCode() + mf.getYear() + mf.getMonitorTime();
        }));
        // 【指标id、行政区划编码、年份、监测时间】相同的组中只取最后一条
        idtMonitorFills = map.values().stream().map(mfl -> mfl.get(mfl.size() - 1)).map(mf -> {
            // 删除相同的记录，避免出现【指标id、行政区划编码、年份、监测时间】都相同的
            this.idtMonitorFillService.delete(mf.getIndicatorsId(), mf.getDivisionCode(), mf.getYear(), mf.getMonitorTime());
            return mf;
        }).collect(Collectors.toList());

        idtMonitorFillService.saveOrUpdateBatch(idtMonitorFills);
        return new AjaxResult(idtMonitorFills);
    }

    /**
     * @描述: 修改
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020-10-20
     **/
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public AjaxResult update(IdtMonitorFill idtMonitorFill) {
        if (idtMonitorFill.getYear() == null && StringUtils.isNotBlank(idtMonitorFill.getMonitorTime().split("-")[0])) {
            idtMonitorFill.setYear(Integer.valueOf(idtMonitorFill.getMonitorTime().split("-")[0]));
        }
        prepareData(idtMonitorFill, false);
        idtMonitorFillService.updateById(idtMonitorFill);
        return new AjaxResult();
    }

    /**
     * @描述: 根据主键删除
     * @入参: id
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020-10-20
     **/
    @PostMapping("/delete")
    @ApiOperation(value = "根据主键删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public AjaxResult delete(String id){
        idtMonitorFillService.removeByIds(Func.toStrList(id));
        return new AjaxResult();
    }

    /**
    * @描述: 获取指标监测值历史记录
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/10/21 16:00
    **/
    @PostMapping("/getHistoryList")
    @ApiOperation(value = "获取指标监测值历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, dataType = "long", paramType = "query", example = "1"),
            @ApiImplicitParam(name = "size", value = "每页显示数量", required = true, dataType = "long", paramType = "query", example = "10"),
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "string", paramType = "query", example = "10"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划代码(4106)", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "indicatorsId", value = "指标ID", required = true, dataType = "string", paramType = "query")
    })
    public AjaxResult getHistoryList(@ApiIgnore Page page, String year, String indicatorsId, String divisionCode){
        // 获取指标数据
        Map<String, String> deptMap = iIdtIndicatorsService.getDeptNameMap();
        IdtIndicators idtIndicators = iIdtIndicatorsService.getById(indicatorsId);
        //处理责任处室多级中文名问题
        if(StringUtils.isNotBlank(idtIndicators.getDutyDepartment())){
            idtIndicators.setDutyDepartment(iIdtIndicatorsService.getDeptNameStr(idtIndicators.getDutyDepartment(), deptMap));
        }
        if(StringUtils.isNotBlank(idtIndicators.getDutyCompany())){
            idtIndicators.setDutyCompany(iIdtIndicatorsService.getDeptNameStr(idtIndicators.getDutyCompany(), deptMap));
        }
        //分页获取当前指标下监测值的更新年份记录
        QueryWrapper<IdtMonitorValue> queryWrapper = new QueryWrapper();
        queryWrapper.select("distinct monitor_time");
        queryWrapper.eq("indicators_id",indicatorsId);
        if(StringUtils.isNotBlank(year)){
            queryWrapper.like("monitor_time", year);
        }
        if(StringUtils.isNotBlank(divisionCode)){
            queryWrapper.eq("division_code", divisionCode);
        }
        queryWrapper.orderByDesc("monitor_time");
        IPage<IdtMonitorValue> iPage = iIdtMonitorValueService.page(page, queryWrapper);
        List<IdtMonitorValue> list = iPage.getRecords();
        if(list.size() == 0 || list.toString().equals("[null]") || list.toString().equals("null")){
            return new AjaxResult();
        }
        //获取分页后的监测时间
        List<IdtMonitorValue> idtMonitorValueList = list.stream().filter(x -> x != null).collect(Collectors.toList());
        List<String> monitorTimeList = idtMonitorValueList.stream().map(x -> x.getMonitorTime()).collect(Collectors.toList());
        iPage.setTotal(monitorTimeList.size());
        //获取各行政区划的指标监测值
        List<IdtMonitorValue> idtMonitorValues = iIdtMonitorValueService.getHistoryList(indicatorsId, monitorTimeList, divisionCode);
        Boolean isFormula = false;
        List<String> idList = new ArrayList<>();
        // 判断是否是复合指标
        if("formula".equals(idtIndicators.getDatasource())){
            if(StringUtils.isBlank(idtIndicators.getCalculateResult())){
                return new AjaxResult(StatusCode.ERROR_CODE_40005,"该复合指标请先配置计算公式");
            }
            isFormula = true;
            QueryWrapper<IdtIndicators> queryWrapper1 = new QueryWrapper();
            List<String> result = RegularUtils.extractString(idtIndicators.getCalculateResult());
            queryWrapper1.in("code",result);
            List<IdtIndicators> indicators = iIdtIndicatorsService.list(queryWrapper1);
            idList = indicators.stream().map(IdtIndicators::getId).collect(Collectors.toList());
        }
        //数据处理，返回指定格式数据
        List<List<Map<String, Object>>> resultList = new ArrayList<>();
        for (String monitorTime:monitorTimeList) {
            List<Map<String, Object>> maps = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            map.put("time", monitorTime);
            maps.add(map);
            for (IdtMonitorValue idtMonitorValue:idtMonitorValues) {
                if(idtMonitorValue.getMonitorTime().equals(monitorTime)){
                    if (StringUtils.isNotBlank(idtMonitorValue.getDivisionName())) {
                        Map<String, Object> m = new HashMap<>();
                        Map<String, Object> value = new HashMap<>();
                        m.put(idtMonitorValue.getDivisionName(), idtMonitorValue.getMonitorValue());
                        value.put("monitorValue", idtMonitorValue.getMonitorValue());
                        value.put("reportValue", "");
                        // 如果是复合指标，则查询该指标关联因子数值
                        if(isFormula){
                            Map<String, Object> mObject = new HashMap<>();
                            List<IdtMonitorValue> monitorValues = iIdtMonitorValueService.listByIndicatorsIds(idList, monitorTime, idtMonitorValue.getDivisionCode());
                            for (IdtMonitorValue r:monitorValues) {
                                mObject.put(r.getIdtName(),r.getMonitorValue());
                            }
                            value.put("formulaData",mObject);
                        }
                        m.put(idtMonitorValue.getDivisionName(), value);
                        //默认只有一条符合条件，便于查看附件
                        m.put("dutyCompany", idtIndicators.getDutyCompany());
                        m.put("explain", idtMonitorValue.getExplain() == null ? null : idtMonitorValue.getExplain());
                        m.put("dutyDepartment",idtIndicators.getDutyDepartment());
                        try {
                            Long id = Long.valueOf(idtMonitorValue.getCreator());
                            m.put("creator", iUserClient.userInfoById(id).getData().getUserName());
                        } catch (Exception e) {
                            m.put("creator", idtMonitorValue.getCreator());
                        }
                        m.put("createTime", idtMonitorValue.getCreateTime() == null ? null : idtMonitorValue.getCreateTime());
                        m.put("reportId", idtMonitorValue.getId());
                        // 判断是否存在附件
                        LambdaQueryWrapper<IdtReportFile> queryWrapper1 = new QueryWrapper().lambda();
                        queryWrapper1.eq(IdtReportFile::getReportId,idtMonitorValue.getId());
                        List<IdtReportFile> idtReportFiles = iIdtReportFileService.list(queryWrapper1);
                        if(idtReportFiles.size() > 0){
                            m.put("reportStatus", true);
                        }else {
                            m.put("reportStatus", false);
                        }
                        maps.add(m);
                    }
                }
            }
            resultList.add(maps);
        }
        //获取当前指标下所有已存在监测值的行政区划
        List<String> nameList = idtMonitorValues.stream().sorted(Comparator.comparing(IdtMonitorValue::getDivisionCode))
                .map(x -> x.getDivisionName()).distinct().collect(Collectors.toList());
        nameList = nameList.stream().filter(s -> StringUtils.isNotBlank(s)).collect(Collectors.toList());
        Map<String, Object> result = new HashMap<>();
        result.put("resultList",resultList);
        result.put("nameList", nameList);
        result.put("iPage",iPage);
        return new AjaxResult(result);
    }

    /**
    * @描述: 导出
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/10/21 18:45
    **/
    @PostMapping("/expHistoryList")
    @ApiOperation(value = "导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, dataType = "long", paramType = "query", example = "1"),
            @ApiImplicitParam(name = "size", value = "每页显示数量", required = true, dataType = "long", paramType = "query", example = "10"),
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划代码(4106)", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "indicatorsId", value = "指标ID", required = true, dataType = "string", paramType = "query")
    })
    public void expHistoryList(@ApiIgnore Page page, String year, String indicatorsId, String divisionCode, HttpServletResponse response){
        // 获取指标数据
        IdtIndicators idtIndicators = iIdtIndicatorsService.getById(indicatorsId);
        Map<String, String> deptMap = iIdtIndicatorsService.getDeptNameMap();
        //处理责任处室多级中文名问题
        if(StringUtils.isNotBlank(idtIndicators.getDutyDepartment())){
            idtIndicators.setDutyDepartment(iIdtIndicatorsService.getDeptNameStr(idtIndicators.getDutyDepartment(), deptMap));
        }
        if(StringUtils.isNotBlank(idtIndicators.getDutyCompany())){
            idtIndicators.setDutyCompany(iIdtIndicatorsService.getDeptNameStr(idtIndicators.getDutyCompany(), deptMap));
        }
        //分页获取当前指标下监测值的更新年份记录
        QueryWrapper<IdtMonitorValue> queryWrapper = new QueryWrapper();
        queryWrapper.select("distinct monitor_time");
        queryWrapper.eq("indicators_id",indicatorsId);
        if(StringUtils.isNotBlank(year)){
            queryWrapper.like("monitor_time", Integer.valueOf(year));
        }
        if(StringUtils.isNotBlank(divisionCode)){
            queryWrapper.eq("division_code", divisionCode);
        }
        queryWrapper.orderByDesc("monitor_time");
        IPage<IdtMonitorValue> iPage = iIdtMonitorValueService.page(page, queryWrapper);
        /*QueryWrapper<IdtMonitorValue> queryWrapper = new QueryWrapper();
        queryWrapper.select("distinct udpate_time");
        queryWrapper.eq("indicators_id",indicatorsId);
        if(StringUtils.isNotBlank(year)){
            queryWrapper.eq("udpate_time", year);
        }
        if(StringUtils.isNotBlank(divisionCode)){
            queryWrapper.eq("division_code", divisionCode);
        }
        queryWrapper.orderByDesc("year");
        IPage<IdtMonitorValue> iPage = iIdtMonitorValueService.page(page, queryWrapper);*/
        List<IdtMonitorValue> list = iPage.getRecords();
        List<String> yearList = list.stream().map(x -> x.getMonitorTime()).collect(Collectors.toList());
        //获取当前指标下所有已存在监测值的行政区划
        List<String> divisionNameList;
        List<IdtMonitorValue> idtMonitorValues = new LinkedList<>();;
        if (yearList == null || yearList.isEmpty()){
            yearList = new LinkedList<>();
            divisionNameList = new LinkedList<>();
        }else{
            //获取各行政区划的指标监测值
            idtMonitorValues = iIdtMonitorValueService.getHistoryList(indicatorsId,yearList,divisionCode);
            //获取当前指标下所有已存在监测值的行政区划
            divisionNameList = idtMonitorValues.stream().map(x -> x.getDivisionName()).distinct().collect(Collectors.toList());
        }
        // 判断该指标是否是复合指标，如果是符合指标，需要查询相关计算因子
        List<String> calculateFactorNameList = new LinkedList<>();
        List<String> calculateFactorIdList = new LinkedList<>();
        if("formula".equals(idtIndicators.getDatasource())){
            if(StringUtils.isBlank(idtIndicators.getCalculateResult())){
                calculateFactorNameList.add("该复合指标请先配置计算公式");
            }
            QueryWrapper<IdtIndicators> queryWrapper1 = new QueryWrapper();
            List<String> result = RegularUtils.extractString(idtIndicators.getCalculateResult());
            queryWrapper1.in("code",result);
            List<IdtIndicators> indicators = iIdtIndicatorsService.list(queryWrapper1);
            // 获取计算因子指标名列表
            calculateFactorNameList = indicators.stream().map(IdtIndicators::getName).collect(Collectors.toList());
            // 获取计算因子指标id列表
            calculateFactorIdList = indicators.stream().map(IdtIndicators::getId).collect(Collectors.toList());
        }

        //组装导出Excel数据
        List<Object[]> dataList = new ArrayList<Object[]>();
        // 遍历每个年份
        for (String time: yearList) {
            // 1 ：日期
            // (1 + calculateFactorIdList.size() + 3 ) * divisionNameList.size() ：（监测值、[因子值]、填写人、填写时间、说明）* 行政区划
            // 2 ： 责任单位、责任处室
            Object[] datas = new Object[1 + (1 + calculateFactorIdList.size() + 3 ) * divisionNameList.size() + 2];
            // 动态数据开始填充的下标，动态数据为检测值、因子的监测值、上报人、上报时间、说明
            int beginIndex = 0;
            // 日期
            datas[beginIndex++] = time;
            // 遍历每个行政区划
            for (String divisionName : divisionNameList) {
                // 指标监测值
                for (IdtMonitorValue idtMonitorValue:idtMonitorValues) {
                    if(idtMonitorValue.getDivisionName().equals(divisionName) && idtMonitorValue.getMonitorTime().equals(time)){
                        // 指标监测值
                        datas[beginIndex++] = idtMonitorValue.getMonitorValue();
                        // 查询因子值
                        if(!calculateFactorIdList.isEmpty()){
                            List<IdtMonitorValue> monitorValues = iIdtMonitorValueService.listByIndicatorsIds(calculateFactorIdList, time, idtMonitorValue.getDivisionCode());
                            for (String calculateFactorId : calculateFactorIdList) {
                                IdtMonitorValue firstReportValue = monitorValues.stream().filter(monitorValue -> {
                                    return monitorValue.getIndicatorsId().equals(calculateFactorId);
                                }).findFirst().orElse(null);
                                datas[beginIndex++] = firstReportValue == null? "":firstReportValue.getMonitorValue();
                            }
                        }
                        try {
                            Long id = Long.valueOf(idtMonitorValue.getCreator());
                            // 填写人
                            datas[beginIndex++] = iUserClient.userInfoById(id).getData().getUserName();
                        } catch (Exception e) {
                            datas[beginIndex++] = idtMonitorValue.getCreator();
                        }

                        // 填写时间
                        datas[beginIndex++] = TimeUtils.formatDate(idtMonitorValue.getCreateTime()) ;
                        // 说明
                        datas[beginIndex++] = idtMonitorValue.getExplain() ;
                        break;
                    }
                }

            }
            // 责任单位，该单元格左边有：日期、各地区动态值（监测值、[因子的监测值]、填写人、填写时间、说明）
            datas[1 + divisionNameList.size() * (1 + calculateFactorIdList.size() + 3) ] = idtIndicators.getDutyCompany() ;
            // 责任处室，该单元格左边有：日期、各地区动态值（检测值、[因子的监测值]、填写人、填写时间、说明）、责任单位
            datas[1 + divisionNameList.size() * (1 + calculateFactorIdList.size() + 3 )  + 1 ] = idtIndicators.getDutyDepartment() ;
            dataList.add(datas);
        }
        // 表格标题
        LinkedList<List<String>> titleConfigs = new LinkedList<>();
        titleConfigs.add(Arrays.asList("0","0","0","2","日期"));
        for (int i = 0; i < divisionNameList.size(); i++) {
            // 各个地区动态数据的开始填充下标，左边有：日期、上一地区动态值（检测值、因子的监测值、填写人、填写时间、说明）
            int beginColIndex = 1 + i * (1 + calculateFactorIdList.size() + 3) ;
            // 地区标题
            titleConfigs.add(Arrays.asList(String.valueOf(beginColIndex),String.valueOf(beginColIndex + 1 + calculateFactorIdList.size() + 3 -1),"0","0",divisionNameList.get(i)));
            // 指标的值标题
            titleConfigs.add(Arrays.asList(String.valueOf(beginColIndex),String.valueOf(beginColIndex),"1","1","指标值"));
            titleConfigs.add(Arrays.asList(String.valueOf(beginColIndex),String.valueOf(beginColIndex),"2","2","监测值"));
            // 计算因子的标题
            if (!calculateFactorIdList.isEmpty()) {
                // beginColIndex : 监测值下标
                // beginColIndex + 1 : 第一个因子值下标
                // beginColIndex + 1 + calculateFactorIdList.size()-1 : 最后一个因子值下标
                titleConfigs.add(Arrays.asList(String.valueOf(beginColIndex + 1),String.valueOf(beginColIndex + 1 + calculateFactorIdList.size()-1),"1","1","因子值"));
                for (int i1 = 0; i1 < calculateFactorNameList.size(); i1++) {
                    titleConfigs.add(Arrays.asList(String.valueOf(beginColIndex + 1 + i1),String.valueOf(beginColIndex + 1 + i1),"2","2",calculateFactorNameList.get(i1)));
                }
            }
            // 填写人、左边有：日期、上一地区动态值（监测值、因子的监测值、填写人、填写时间、说明），上一地区动态值（检测值、因子的监测值）
            titleConfigs.add(Arrays.asList(String.valueOf(beginColIndex + 1 + calculateFactorIdList.size())
                    ,String.valueOf(beginColIndex + 1 + calculateFactorIdList.size()),"1","2","填写人"));
            // 填写时间、左边有：日期、上一地区动态值（监测值、因子的监测值、填写人、填写时间、说明），上一地区动态值（检测值、因子的监测值、填写人）
            titleConfigs.add(Arrays.asList(String.valueOf(beginColIndex + 1 + calculateFactorIdList.size() + 1)
                    ,String.valueOf(beginColIndex + 1 + calculateFactorIdList.size() + 1),"1","2","填写时间"));
            // 说明、左边有：日期、上一地区动态值（监测值、因子的监测值、填写人、填写时间、说明），上一地区动态值（检测值、因子的监测值、填写人、填写时间）
            titleConfigs.add(Arrays.asList(String.valueOf(beginColIndex + 1 + calculateFactorIdList.size() + 2)
                    ,String.valueOf(beginColIndex + 1 + calculateFactorIdList.size() + 2),"1","2","说明"));
        }
        // 固定数据开始填充的下标，左边有：日期、各地区动态值（检测值、因子的监测值、填写人、填写时间、说明）
        int beginColIndex2 = 1 + divisionNameList.size() * (1 + calculateFactorIdList.size() + 3);
        titleConfigs.add(Arrays.asList(String.valueOf(beginColIndex2),String.valueOf(beginColIndex2),"0","2","责任单位"));
        titleConfigs.add(Arrays.asList(String.valueOf(beginColIndex2 + 1),String.valueOf(beginColIndex2 + 1),"0","2","责任处室"));
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        ExcelUtil.exportExcel(response, "监测指标", "监测指标信息", titleConfigs, dataList,3);
    }

    /**
    * @描述: 监测值临时表数据验证
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/10/22 10:20
    **/
    @PostMapping("/isExistsMonitorFill")
    @ApiOperation(value = "监测值临时表数据验证")
    public AjaxResult isExistsMonitorFill(MultipartFile multipartFile) throws Exception {
        String deptId = this.getUser().getDeptId();
        if (StringUtils.isBlank(deptId)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该用户所属部门不存在");
        }
        if (multipartFile.isEmpty()) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "导入文件不能为空！");
        }
        // 根据上传MultipartFile对象获取excel数据集
        List<List<String>> excelList = ExcelUtil.getExcelData(multipartFile);
        // 数据预处理
        AjaxResult prepareExcelData = this.prepareExcelData(excelList);
        if (prepareExcelData != null){
            return prepareExcelData;
        }
        // 重复数据
        List<IdtMonitorFill> repeatingData = new ArrayList<>();
        for (int i = 1; i < excelList.size(); i++) {
            List<String> dataList = excelList.get(i);
            String idtCode = dataList.get(0);
            LambdaQueryWrapper<IdtIndicators> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.eq(IdtIndicators::getCode, idtCode);
            IdtIndicators idtIndicators = iIdtIndicatorsService.getOne(queryWrapper);
            IdtMonitorFill idtMonitorFill = new IdtMonitorFill();
            idtMonitorFill.setIdtCode(idtCode);
            if(StringUtils.isNotBlank(dataList.get(4))){
                String divisionCode = dataList.get(4).indexOf(".") != -1 ? dataList.get(4).substring(0, dataList.get(4).indexOf(".")) : dataList.get(4);
                idtMonitorFill.setDivisionCode(divisionCode);
            }
            idtMonitorFill.setMonitorValue(dataList.get(5));
            if(StringUtils.isNotBlank(dataList.get(6))){
                String monitorTime = dataList.get(6).indexOf(".") >= 0 ? dataList.get(6).substring(0, dataList.get(6).indexOf(".")) : dataList.get(6);
                idtMonitorFill.setYear(Integer.parseInt(monitorTime.substring(0, 4 )));
                idtMonitorFill.setMonitorTime(monitorTime);
            }else {
                return new AjaxResult(StatusCode.ERROR_CODE_40005, "第"+(i+1)+"行采集时间不能为空，请检查");
            }
            idtMonitorFill.setId(UuidUtil.get32UUID());
            idtMonitorFill.setOrgId(deptId);
            if (idtIndicators != null) {
                //判断是否存在相同指标id与行政区划编码与相同年份
                LambdaQueryWrapper<IdtMonitorFill> queryWrapper1 = new QueryWrapper().lambda();
                queryWrapper1.eq(IdtMonitorFill::getYear, idtMonitorFill.getYear());
                queryWrapper1.eq(IdtMonitorFill::getDivisionCode, idtMonitorFill.getDivisionCode());
                queryWrapper1.eq(IdtMonitorFill::getIndicatorsId, idtIndicators.getId());
                //采集时间验证
                if(!TimeUtils.verifyUpdateTime(idtIndicators.getUpdateCycle(), idtMonitorFill.getMonitorTime())){
                    return new AjaxResult(StatusCode.ERROR_CODE_40005, "第"+(i+1)+"行监测时间格式不正确，请检查");
                }
                queryWrapper1.eq(IdtMonitorFill::getMonitorTime, idtMonitorFill.getMonitorTime());
                List<IdtMonitorFill> sourceIdtMonitorValueList = idtMonitorFillService.list(queryWrapper1);
                if (sourceIdtMonitorValueList.size() > 0) {
                    repeatingData.add(idtMonitorFill);
                }
                // 2021-10-08 陈宏成 取消指标导入时，责任处室的检验判断
//                // 20210701--新增当前用户所属机构与指标的责任处室不一致时，直接给出提示
//                List<Dept> deptList = iSysClient.getDeptChild(Long.valueOf(idtIndicators.getDutyDepartment())).getData();
//                String deptIds = deptList.stream().map(x->x.getId()+"").collect(Collectors.joining(","));
//                if(StringUtils.isNotBlank(deptIds) && deptIds.indexOf(deptId) == -1){
//                    return new AjaxResult(StatusCode.ERROR_CODE_40005, "导入指标的责任处室与当前用户所属处室不一致，请检查填报指标！");
//                }
            }
        }
        String resultCodes = "";
        for (IdtMonitorFill obj : repeatingData) {
            if (!resultCodes.contains(obj.getIdtCode())) {
                resultCodes += StringUtils.isBlank(resultCodes) ? obj.getIdtCode() : "," + obj.getIdtCode();
            }
        }
        return new AjaxResult(resultCodes);
    }

    /**
    * @描述: 指标监测值导入
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/10/22 9:28
    **/
    @PostMapping("/importExcel")
    @ApiOperation(value = "导入Excel")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importExcel(MultipartFile multipartFile, Boolean isUpdate) throws Exception {
        // 根据上传MultipartFile对象获取excel数据集
        List<List<String>> excelList = ExcelUtil.getExcelData(multipartFile);
        // 数据预处理
        AjaxResult prepareExcelData = this.prepareExcelData(excelList);
        if (prepareExcelData != null){
            return prepareExcelData;
        }
        // 存储新增、更新指标集合
        List<IdtMonitorFill> saveUpdateList = new ArrayList<>();
        for (int i = 1; i < excelList.size(); i++) {
            List<String> dataList = excelList.get(i);
            String idtCode = dataList.get(0);
            LambdaQueryWrapper<IdtIndicators> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.eq(IdtIndicators::getCode, idtCode);
            IdtIndicators idtIndicators = iIdtIndicatorsService.getOne(queryWrapper);
            IdtMonitorFill idtMonitorFill = new IdtMonitorFill();

            if(StringUtils.isNotBlank(dataList.get(4))){
                //可能读成数字了，带小数，去掉小数
                String divisionCode = dataList.get(4).indexOf(".") != -1 ? dataList.get(4).substring(0, dataList.get(4).indexOf(".")) : dataList.get(4);
                idtMonitorFill.setDivisionCode(divisionCode);
            }
            idtMonitorFill.setMonitorValue(dataList.get(5));
            if(StringUtils.isNotBlank(dataList.get(6))){
                String monitorTime = dataList.get(6).indexOf(".") >= 0 ? dataList.get(6).substring(0, dataList.get(6).indexOf(".")) : dataList.get(6);
                idtMonitorFill.setYear(Integer.parseInt(monitorTime.substring(0, 4 )));
                idtMonitorFill.setMonitorTime(monitorTime);
            }else {
                return new AjaxResult(StatusCode.ERROR_CODE_40005, "第"+(i+1)+"行采集时间不能为空，请检查");
            }
            idtMonitorFill.setExplain(dataList.get( 7));
            idtMonitorFill.setId(UuidUtil.get32UUID());
            idtMonitorFill.setOrgId(this.getUser().getDeptId());
            if (idtIndicators != null) {
                //判断是否存在相同指标id与行政区划编码与相同年份
                LambdaQueryWrapper<IdtMonitorFill> queryWrapper1 = new QueryWrapper().lambda();
                queryWrapper1.eq(IdtMonitorFill::getYear, idtMonitorFill.getYear());
                queryWrapper1.eq(IdtMonitorFill::getDivisionCode, idtMonitorFill.getDivisionCode());
                queryWrapper1.eq(IdtMonitorFill::getIndicatorsId, idtIndicators.getId());
                //采集时间精确到天 根据天查
                queryWrapper1.eq(IdtMonitorFill::getMonitorTime, idtMonitorFill.getMonitorTime());
                List<IdtMonitorFill> sourceIdtMonitorValueList = idtMonitorFillService.list(queryWrapper1);
                if (sourceIdtMonitorValueList.size() > 0) {
                    if(isUpdate != null && isUpdate){
                        IdtMonitorFill monitorValue = sourceIdtMonitorValueList.get(0);
                        monitorValue.setMonitorValue(idtMonitorFill.getMonitorValue());
                        idtMonitorFill = monitorValue;
                    }else{
                        continue;
                    }
                }
                idtMonitorFill.setUnit(idtIndicators.getUnit());
                idtMonitorFill.setIndicatorsId(idtIndicators.getId());
                idtMonitorFill.setIdtCode(idtIndicators.getCode());
                prepareData(idtMonitorFill, true);
                // 检查这个指标这个年份和行政区划是否在有对应的指标体系，如果没有，则不保存
                List<IdtIndicatorsType> idtTypeList = this.iIdtIndicatorsTypeService.findTypeForIdt(null, idtMonitorFill.getIndicatorsId(), idtMonitorFill.getYear(), idtMonitorFill.getDivisionCode());
                if (!CollectionUtils.isEmpty(idtTypeList)){
                    // 2021-12-24 过滤掉excel表里面【指标id、行政区划、年份、监测时间】相同的记录
                    IdtMonitorFill temp = idtMonitorFill;
                    saveUpdateList = saveUpdateList.stream().filter(mv -> {
                        return !(Objects.equals(mv.getIndicatorsId(), temp.getIndicatorsId())
                                && Objects.equals(mv.getYear(), temp.getYear())
                                && Objects.equals(mv.getMonitorTime(), temp.getMonitorTime())
                                && Objects.equals(mv.getDivisionCode(), temp.getDivisionCode()));
                    }).collect(Collectors.toList());
                    saveUpdateList.add(idtMonitorFill);
                }
            }
        }
        if (saveUpdateList.size() > 0) {
            saveUpdateList = saveUpdateList.stream().map(mf -> {
                // 删除相同的记录，避免出现【指标id、行政区划编码、年份、监测时间】都相同的
                this.idtMonitorFillService.delete(mf.getIndicatorsId(), mf.getDivisionCode(), mf.getYear(), mf.getMonitorTime());
                return mf;
            }).collect(Collectors.toList());
            // 批量保存更新
            idtMonitorFillService.saveOrUpdateBatch(saveUpdateList);
            // 更新指标表中排序
            List<String> ids = saveUpdateList.stream().map(x->x.getIndicatorsId()).collect(Collectors.toList());
            iIdtIndicatorsService.updateSortStatus(ids, this.getUser().getUserId().toString(), 1);
        }
        return new AjaxResult(saveUpdateList);
    }

    /**
    * @描述: 发布数据验证
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/10/22 14:29
    **/
    @PostMapping("/isExistsMonitor")
    @ApiOperation(value = "发布数据验证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "indicatorsId", value = "指标ID（多个使用逗号隔开）", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "idtCode", value = "指标编码（多个使用逗号隔开）", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userDivision", value = "行政区划编码(多个使用逗号隔开)", required = true, dataType = "string", paramType = "query")
    })
    public AjaxResult isExistsMonitor(String indicatorsId, String idtCode, String userDivision) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        String[] indicatorsIds = iIdtIndicatorsService.listInIndicatorsIds(indicatorsId);
        Map<String, String> deptMap = iIdtIndicatorsService.getDeptNameMap();
        String[] userDivisions = userDivision.split(",");
        // 重复数据
        List<IdtMonitorValue> repeatingData = new ArrayList<>();
        for (int i = 0; i < indicatorsIds.length; i++) {
            IdtIndicators idtIndicators = iIdtIndicatorsService.getById(indicatorsIds[i]);
            //获取指标监测值列表数据
            List<IdtMonitorFill> idtMonitorFills = idtMonitorFillService.listByData(indicatorsIds[i], userDivisions);
            for (IdtMonitorFill idtMonitorFill:idtMonitorFills) {
                IdtMonitorValue idtMonitorValue = new IdtMonitorValue();
                BeanUtils.copyProperties(idtMonitorFill, idtMonitorValue);
                // idtMonitorValue.setIdtCode(code);
                idtMonitorValue.setIdtName(idtIndicators.getName());
                idtMonitorValue.setIdtCode(idtIndicators.getCode());
                idtMonitorValue.setMonitorValue(idtMonitorFill.getMonitorValue());

                LambdaQueryWrapper<IdtMonitorValue> queryWrapper = new QueryWrapper().lambda();
                queryWrapper.eq(IdtMonitorValue::getYear, idtMonitorFill.getYear());
                queryWrapper.eq(IdtMonitorValue::getDivisionCode, idtMonitorFill.getDivisionCode());
                queryWrapper.eq(IdtMonitorValue::getIndicatorsId, indicatorsIds[i]);
                queryWrapper.eq(IdtMonitorValue::getMonitorTime, idtMonitorFill.getMonitorTime());
                List<IdtMonitorValue> sourceIdtMonitorValueList = iIdtMonitorValueService.list(queryWrapper);

                if (sourceIdtMonitorValueList.size() > 0) {
                    idtMonitorValue.setOldValue(sourceIdtMonitorValueList.get(0).getMonitorValue());
                    idtMonitorValue.setId(sourceIdtMonitorValueList.get(0).getId());
                    idtMonitorValue.setIdtDutyDepartment(iIdtIndicatorsService.getDeptNameStr(idtIndicators.getDutyDepartment(), deptMap));
                    idtMonitorValue.setIdtDutyCompany(iIdtIndicatorsService.getDeptNameStr(idtIndicators.getDutyCompany(), deptMap));
                    repeatingData.add(idtMonitorValue);
                }
            }
        }

        String resultCodes = "";
        for (IdtMonitorValue obj : repeatingData) {
            if (!resultCodes.contains(obj.getIdtName())) {
                resultCodes += StringUtils.isBlank(resultCodes) ? (obj.getIdtName()+ "("+obj.getIdtDutyCompany()+")" ):
                        "," + (obj.getIdtName()+ "("+obj.getIdtDutyCompany()+")" );
            }
        }

        resultMap.put("resultCodes",resultCodes);
        resultMap.put("repeatingData",repeatingData);

        return new AjaxResult(resultMap);
    }

    /**
    * @描述: 发布
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/10/22 17:22
    **/
    @PostMapping("/publishMonitor")
    @ApiOperation(value = "发布")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "indicatorsId", value = "指标ID（多个使用逗号隔开）", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "idtCode", value = "指标编码（多个使用逗号隔开）", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userDivision", value = "行政区划编码(多个使用逗号隔开)", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "repeatIds", value = "需更新数值（多个使用逗号隔开）", required = true, dataType = "string", paramType = "query")
    })
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult publishMonitor(String indicatorsId, String idtCode, String userDivision, String repeatIds) throws Exception {
        String[] userDivisions = userDivision.split(",");
        String[] indicatorsIds = iIdtIndicatorsService.listInIndicatorsIds(indicatorsId);
        // 存储新增、更新指标集合
        List<IdtMonitorValue> saveUpdateList = new ArrayList<>();
        // 存储发布后需删除的指标监测值
        List<String> delIds = new ArrayList<>();

        // 需要上报现状值的指标集合
        List<IdtReportValue> reportValueList = new ArrayList<>();

        LambdaQueryWrapper<IdtYearRelevance> yearWrapper = (new QueryWrapper()).lambda();
        yearWrapper.in(IdtYearRelevance::getIndicatorsId, indicatorsIds);
        List<IdtYearRelevance> yearRelevanceList = iIdtYearRelevanceService.list(yearWrapper);

        LambdaQueryWrapper<IdtTargetValue> targetWrapper = (new QueryWrapper()).lambda();
        targetWrapper.in(IdtTargetValue::getIndicatorsId, indicatorsIds);
        List<IdtTargetValue> targetValueList = idtTargetValueService.list();

        for (int i = 0; i < indicatorsIds.length; i++) {

            //查询预警规则
            IdtWarnRule warnRule = iIdtWarnRuleService.listWarnRuleById(indicatorsIds[i]);

            //获取指标监测值列表数据
            List<IdtMonitorFill> idtMonitorFills = idtMonitorFillService.listByData(indicatorsIds[i], userDivisions);
            for (IdtMonitorFill idtMonitorFill:idtMonitorFills) {


                // 监测值发布
                delIds.add(idtMonitorFill.getId());
                IdtMonitorValue idtMonitorValue = new IdtMonitorValue();
                BeanUtils.copyProperties(idtMonitorFill, idtMonitorValue);
                idtMonitorValue.setId(UuidUtil.get32UUID());
                LambdaQueryWrapper<IdtMonitorValue> queryWrapper = new QueryWrapper().lambda();
                queryWrapper.eq(IdtMonitorValue::getYear, idtMonitorFill.getYear());
                queryWrapper.eq(IdtMonitorValue::getDivisionCode, idtMonitorFill.getDivisionCode());
                queryWrapper.eq(IdtMonitorValue::getIndicatorsId, indicatorsIds[i]);
                queryWrapper.eq(IdtMonitorValue::getMonitorTime, idtMonitorFill.getMonitorTime());
                List<IdtMonitorValue> sourceIdtMonitorValueList = iIdtMonitorValueService.list(queryWrapper);
                if (sourceIdtMonitorValueList.size() > 0) {
                    if(repeatIds != null && repeatIds.contains(sourceIdtMonitorValueList.get(0).getId())){
                        IdtMonitorValue monitorValue = sourceIdtMonitorValueList.get(0);
                        monitorValue.setMonitorValue(idtMonitorValue.getMonitorValue());
                        monitorValue.setExplain(idtMonitorValue.getExplain());
                        idtMonitorValue = monitorValue;
                        idtMonitorValue.setCreator(null);
                        idtMonitorValue.setCreateTime(null);
                        idtMonitorValue.setModifier(this.getUser().getUserId().toString());
                        idtMonitorValue.setModifyTime(new Date());
                    }else {
                        continue;
                    }
                }else{
                    idtMonitorValue.setCreator(this.getUser().getUserId().toString());
                    idtMonitorValue.setCreateTime(new Date());
                }
                String warnName = JudgeWarnRuleUtil.getWarnName(yearRelevanceList, targetValueList, warnRule, idtMonitorValue.getMonitorValue(), idtMonitorFill.getYear(), idtMonitorFill.getDivisionCode(), indicatorsIds[i]);
                idtMonitorValue.setWarnStatus(warnName);

                // 是否上报现状评估值
                if (idtMonitorFill.getIsReport() != null && idtMonitorFill.getIsReport() == 1) {
                    IdtReportValue idtReportValue = new IdtReportValue();
                    idtReportValue.setId(UuidUtil.get32UUID());
                    idtReportValue.setYear(idtMonitorFill.getYear());
                    idtReportValue.setDivisionCode(idtMonitorFill.getDivisionCode());
                    idtReportValue.setValue(idtMonitorFill.getMonitorValue());
                    idtReportValue.setExplain(idtMonitorFill.getExplain());
                    idtReportValue.setIndicatorsId(idtMonitorFill.getIndicatorsId());
                    idtReportValue.setOrgId(idtMonitorFill.getOrgId());
                    idtReportValue.setCreator(this.getUser().getUserId().toString());
                    idtReportValue.setCreateTime(new Date());

                    LambdaQueryWrapper<IdtReportValue> queryWrapper1 = new QueryWrapper().lambda();
                    queryWrapper1.eq(IdtReportValue::getYear,idtReportValue.getYear());
                    queryWrapper1.eq(IdtReportValue::getDivisionCode,idtReportValue.getDivisionCode());
                    queryWrapper1.eq(IdtReportValue::getIndicatorsId,indicatorsIds[i]);
                    List<IdtReportValue> sourceIdtReportValueList = iIdtReportValueService.list(queryWrapper1);
                    // TODO 2021/03/24 这里暂时先改成只要监测值发布成功了，那上报值也要成功。后面再修改成上报值存在也要提示用户
                    if (sourceIdtReportValueList.size() > 0) {
                        // 如果监测值发布成功了，那上报值也要成功，如果上报值重复，那就覆盖更新
                        IdtReportValue reportValue = sourceIdtReportValueList.get(0);
                        reportValue.setValue(idtReportValue.getValue());
                        reportValue.setExplain(idtReportValue.getExplain());
                        idtReportValue = reportValue;
                        idtReportValue.setCreator(null);
                        idtReportValue.setCreateTime(null);
                        idtReportValue.setModifier(this.getUser().getUserId().toString());
                        idtReportValue.setModifyTime(new Date());
                    }else{
                        // 如果监测值发布成功了，那上报值也要成功
                        idtReportValue.setCreator(this.getUser().getUserId().toString());
                        idtReportValue.setCreateTime(new Date());
                    }
                    //判断是否统一
                    Integer unify = iIdtReportValueService.isUnify(idtReportValue.getIndicatorsId(), idtReportValue.getYear() + "", idtReportValue.getDivisionCode(), idtReportValue.getValue());
                    idtReportValue.setIsUnify(unify);
                    //判断是否达标
                    Integer standard = iIdtReportValueService.isStandard(idtReportValue.getIndicatorsId(), idtReportValue.getYear() + "", idtReportValue.getDivisionCode(), idtReportValue.getValue());
                    idtReportValue.setIsStandard(standard);

                    // 设置现状评估上报的附件关联信息
                    Map map = new HashMap();
                    map.put("report_id",idtMonitorFill.getId());
                    List<IdtReportFile> saveList = new ArrayList<>();
                    List<IdtReportFile> idtReportFiles = (List<IdtReportFile>)idtReportFileService.listByMap(map);
                    if (idtReportFiles != null && idtReportFiles.size() > 0) {
                        for (IdtReportFile idtReportFile : idtReportFiles) {
                            IdtReportFile file = new IdtReportFile();
                            BeanUtils.copyProperties(idtReportFile, file);
                            file.setId(UuidUtil.get32UUID());
                            file.setReportId(idtReportValue.getId());
                            file.setFillType(1);
                            saveList.add(file);
                        }
                    }
                    idtReportFileService.saveOrUpdateBatch(saveList);
                    // 上报值添加进更新列表
                    reportValueList.add(idtReportValue);
                }

                //将临时表附件关联到指标上报表
                iIdtReportFileService.updateByReportId(idtMonitorFill.getId(), idtMonitorValue.getId());

                saveUpdateList.add(idtMonitorValue);
            }
        }
        if (reportValueList.size() > 0) {
            // 批量保存更新
            iIdtReportValueService.saveOrUpdateBatch(reportValueList);
            // 更新指标表中的更新状态
            iIdtIndicatorsService.updateReportStatus(indicatorsId);
        }
        if (saveUpdateList.size() > 0) {
            // 批量保存更新
            iIdtMonitorValueService.saveOrUpdateBatch(saveUpdateList);
            //修改统一率字段
            for (IdtMonitorValue idtMonitorValue: saveUpdateList) {
                //更新对应年份的上报值的是否统一字段
                iIdtReportValueService.updateUnify(idtMonitorValue.getIndicatorsId(), idtMonitorValue.getYear() + "", idtMonitorValue.getDivisionCode());
            }
            // 更新指标表中的更新状态
            iIdtIndicatorsService.updateStatus(indicatorsId);
            // 清理临时表数据
            idtMonitorFillService.removeByIds(delIds);
            //更新指标表中的排序状态
            iIdtIndicatorsService.updateSortStatus(Arrays.asList(indicatorsIds), this.getUser().getUserId().toString(), 0);
        }
        return new AjaxResult(saveUpdateList);
    }

    /**
    * @描述: 判断是否存在待更新或已超时数据
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/10/26 9:22
    **/
    @PostMapping("/isExistData")
    @ApiOperation(value = "判断是否存在待更新或已超时数据")
    public AjaxResult isExistData(){
        QueryWrapper<IdtIndicators> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("datasource","hand");
        List<IdtIndicators> idtIndicatorsList = iIdtIndicatorsService.list(queryWrapper);
        Optional<IdtIndicators> optional = idtIndicatorsList.stream().filter(x -> !"0".equals(x.getUpdateStatus())&&StringUtils.isNotBlank(x.getUpdateStatus())).findFirst();
        if(optional.isPresent()){
            return new AjaxResult(true);
        }
        return new AjaxResult(false);
    }

    private void prepareData(IdtMonitorFill idtMonitorFill, boolean isSave) {
        if(isSave){
            idtMonitorFill.setCreator(this.getUser().getUserId().toString());
            idtMonitorFill.setCreateTime(new Date());
            //防止误修改
            idtMonitorFill.setModifier(null);
            idtMonitorFill.setModifyTime(null);
        }else{
            idtMonitorFill.setModifier(this.getUser().getUserId().toString());
            idtMonitorFill.setModifyTime(new Date());
            //防止误修改
            idtMonitorFill.setCreator(null);
            idtMonitorFill.setCreateTime(null);
        }
    }

    /**
     * 检查数据是否合法
     * @param monitorFills 要检查的数据
     * @return null -- 没问题，非null -- 错误信息
     * @author 陈宏成
     * @date 2021-12-28
     */
    private AjaxResult checkDataLegitimate(List<IdtMonitorFill> monitorFills){
        for(IdtMonitorFill monitorFill : monitorFills) {
            if (StringUtils.isBlank(monitorFill.getIndicatorsId())){
                return new AjaxResult(StatusCode.ERROR_CODE_40005, "指标ID不能为空");
            }
            if (StringUtils.isBlank(monitorFill.getMonitorValue())){
                return new AjaxResult(StatusCode.ERROR_CODE_40005, "监测值不能为空");
            }
            if (StringUtils.isBlank(monitorFill.getDivisionCode())){
                return new AjaxResult(StatusCode.ERROR_CODE_40005, "行政区划不能为空");
            }
            if (StringUtils.isBlank(monitorFill.getMonitorTime())){
                return new AjaxResult(StatusCode.ERROR_CODE_40005, "监测时间不能为空");
            }
        }
        return null;
    }

    /**
     * 处理Excel导入的数据
     * @param excelList Excel表格读取出来的数据
     * @return null -- 没问题，非null -- 错误信息
     * @author 陈宏成
     * @date 2021-12-28
     */
    private AjaxResult prepareExcelData(List<List<String>> excelList){
        if (CollectionUtils.isEmpty(excelList) || excelList.size() <= 1){
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "导入文件数据为空！");
        }
        // 去除数据的前后空格
        for(int j = 1; j < excelList.size(); j++) {
            List<String> rowList = excelList.get(j);
            // 对每个单元格进行去除空格
            for(int i = 0; i < rowList.size(); i++) {
                if(rowList.get(i) == null){
                    rowList.set(i,"");
                }else{
                    rowList.set(i,rowList.get(i).trim());
                }
            }
            // 去除指标编码的小数点
            int idtCodeIndex = 0;
            if(StringUtils.isBlank(rowList.get(idtCodeIndex))){
                return new AjaxResult(StatusCode.ERROR_CODE_40005, String.format("第 %s 行指标编码为空，请补充完整。", j + 1));
            }else if (rowList.get(idtCodeIndex).contains(".")){
                rowList.set(idtCodeIndex, rowList.get(idtCodeIndex).substring(0, rowList.get(idtCodeIndex).indexOf(".") ));
            }
            // 去除行政区划编码的小数点
            int divisionCodeIndex = 4;
            if(StringUtils.isBlank(rowList.get(divisionCodeIndex))){
                return new AjaxResult(StatusCode.ERROR_CODE_40005, String.format("第 %s 行行政区划编码为空，请补充完整。", j + 1));
            }else if (rowList.get(divisionCodeIndex).contains(".")){
                rowList.set(divisionCodeIndex, rowList.get(divisionCodeIndex).substring(0, rowList.get(divisionCodeIndex).indexOf(".") ));
            }
            // 去除年份的小数点
            int yearIndex = 6;
            if(StringUtils.isBlank(rowList.get(yearIndex))){
                return new AjaxResult(StatusCode.ERROR_CODE_40005, String.format("第 %s 行监测时间为空，请补充完整。", j + 1));
            }else if (rowList.get(yearIndex).contains(".")){
                rowList.set(yearIndex, rowList.get(yearIndex).substring(0, rowList.get(yearIndex).indexOf(".") ));
            }
            // 检查监测值值是否为空
            int valueIndex = 5;
            if(StringUtils.isBlank(rowList.get(valueIndex))){
                return new AjaxResult(StatusCode.ERROR_CODE_40005, String.format("第 %s 行监测值为空，请补充完整。", j + 1));
            }
        }
        return null;
    }
}
